//
//  NSString+YC.m
//  YCSchool
//
//  Created by yanglinxia on 16/4/26.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//

#import "NSString+YC.h"
#import "NSData+YC.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (YC)

// 去掉两端的空格
- (NSString *)yc_trimString
{
    NSCharacterSet *characterSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    return [self stringByTrimmingCharactersInSet:characterSet];
}

- (BOOL)yc_canOpenURL
{
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:self]];
}

- (BOOL)yc_openURL
{
    return [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self]];
}

- (NSDate *)yc_dateWithDateFormatString:(NSString *)formatString
{
    if(!formatString)
    {
        return nil;
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = formatString;
    return [formatter dateFromString:self];
}

- (CGSize)yc_sizeWithFont:(UIFont *)font MaxSize:(CGSize)size
{
    NSDictionary *dict = @{NSFontAttributeName:font};
    return [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;

}


- (NSString *)yc_md5String
{
    const char *str = [self UTF8String];
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    return filename;
}

- (NSUInteger)yc_wordCount
{
    NSUInteger i,n=[self length],l=0,a=0,b=0;
    unichar c;
    for(i=0;i<n;i++)
    {
        c = [self characterAtIndex:i];
        if(isblank(c))
        {
            b++;
        }
        else if(isascii(c)){
            a++;
        }
        else
        {
            l++;
        }
    }
    if( a == 0 && l == 0) return 0;
    return l+(NSUInteger)ceilf((CGFloat)(a+b)/2.0);
}

- (NSString *)yc_paramOfName:(NSString *)paramName
{
    if (![paramName hasSuffix:@"="])
    {
        paramName = [NSString stringWithFormat:@"%@=", paramName];
    }
    
    NSString * str = nil;
    NSRange start = [self rangeOfString:paramName];
    if (start.location != NSNotFound)
    {
        // confirm that the parameter is not a partial name match
        unichar c = '?';
        if (start.location != 0)
        {
            c = [self characterAtIndex:start.location - 1];
        }
        if (c == '?' || c == '&' || c == '#')
        {
            NSRange end = [[self substringFromIndex:start.location+start.length] rangeOfString:@"&"];
            NSUInteger offset = start.location+start.length;
            str = end.location == NSNotFound ?
            [self substringFromIndex:offset] :
            [self substringWithRange:NSMakeRange(offset, end.location)];
            str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
    }
    return str;
}

- (NSString *)yc_stringOfHexString
{
    return [[NSString alloc] initWithData:[self yc_dataUsingHexEncoding] encoding:NSASCIIStringEncoding];
}

- (NSString *)yc_hexString
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    return [data yc_hexStringOfData];
}

- (NSData *)yc_dataUsingHexEncoding
{
    NSMutableData *stringData = [[NSMutableData alloc] init];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i = 0; i < [self length] / 2; i++) {
        byte_chars[0] = [self characterAtIndex:i*2];
        byte_chars[1] = [self characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [stringData appendBytes:&whole_byte length:1];
    }
    return [stringData copy];
}

- (NSString *)yc_urlEncodeString
{
    return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                                                     kCFAllocatorDefault,
                                                                     //将当前objectC字符串转为CF字符串
                                                                     (__bridge CFStringRef)self,
                                                                     NULL,
                                                                     //被编码的字符
                                                                     CFSTR("!?&+=%# |"),
                                                                     kCFStringEncodingUTF8));
}

- (id)yc_JSONObject
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    return object;
}

- (NSString *)yc_decrypt3DESWithKey:(NSString *)key IV:(NSString *)iv
{
    NSData *data = [self yc_dataUsingHexEncoding];
    data = [data yc_crypto3des:kCCDecrypt key:key.UTF8String iv:iv.UTF8String];
    NSString *plainText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return plainText;
}

- (NSString *)yc_encrypt3DESWithKey:(NSString *)key IV:(NSString *)iv
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    data = [data yc_crypto3des:kCCEncrypt key:key.UTF8String iv:iv.UTF8String];
    NSString *hexString = [data yc_hexStringOfData];
    return hexString;
}

- (NSDictionary *)yc_PINYINInfo
{
    if(self.length < 1)
    {
        return nil;
    }
    
    CFMutableStringRef string = CFStringCreateMutableCopy(NULL, 0, (CFStringRef)self.yc_trimString);
    CFStringTransform(string, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform(string, NULL, kCFStringTransformStripDiacritics, NO);
    NSString *pinyin = (id)CFBridgingRelease(string);
    NSString *firstLetter = [pinyin substringWithRange:NSMakeRange(0, 1)].uppercaseString;
    NSMutableString *key = [[NSMutableString alloc] init];
    NSArray *words = [pinyin componentsSeparatedByString:@" "];
    for(NSString *word in words)
    {
        NSString *k = @"";
        if(word.length > 1)
        {
            k = [word substringWithRange:NSMakeRange(0, 1)].uppercaseString;
        };
        [key appendString:k];
    }
    
    NSDictionary *info = @{@"pinyin":pinyin.uppercaseString,@"key":[key copy],@"letter":firstLetter};
    return info;
}

+ (NSString *)yc_guidString
{
    CFUUIDRef uuidObj = CFUUIDCreate(nil);
    NSString *uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(nil, uuidObj);
    CFRelease(uuidObj);
    uuidString = [uuidString stringByReplacingOccurrencesOfString:@"-" withString:@""];
    uuidString = [uuidString lowercaseString];
    return uuidString ;
}

- (NSString *)yc_RSADecryptWithPublicKeyRef:(SecKeyRef)keyRef
{
    NSData *data = [GTMBase64 decodeData:[self dataUsingEncoding:NSUTF8StringEncoding]];
    NSData *decryptData = [data yc_RSADecryptWithPublicKeyRef:keyRef];
    NSString *ret = [[NSString alloc] initWithData:decryptData encoding:NSUTF8StringEncoding];
    return ret;
}

- (NSString *)yc_RSAEncryptWithPublicKeyRef:(SecKeyRef)keyRef
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSData *encryptData = [data yc_RSAEncryptWithPublicKeyRef:keyRef];
    NSString *ret = [[NSString alloc] initWithData:[GTMBase64 encodeData:encryptData] encoding:NSUTF8StringEncoding];
    return ret;
}

- (NSString *)yc_AES256DecryptWithKey:(NSString *)key
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSData *decryptData = [data yc_AES256DecryptWithKey:key];
    NSString *string = [[NSString alloc] initWithData:decryptData encoding:NSUTF8StringEncoding];
    return string;
}

- (NSString *)yc_AES256EncryptWithKey:(NSString *)key
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSData *encryptData = [data yc_AES256EncryptWithKey:key];
    NSString *string = [[NSString alloc] initWithData:encryptData encoding:NSUTF8StringEncoding];
    return string;
}

- (NSString *)yc_urlStringWithParams:(NSDictionary *)params
{
    if(params.count < 1)
    {
        return self;
    }
    
    NSMutableArray *ps = [[NSMutableArray alloc] init];
    [params enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSString *kv = [NSString stringWithFormat:@"%@=%@",key,[[obj description] yc_urlEncodeString]];
        [ps addObject:kv];
    }];
    NSURL *u = [NSURL URLWithString:self];
    NSString *url;
    if(u.query)
    {
        if([self hasSuffix:@"&"])
        {
            url = [NSString stringWithFormat:@"%@%@",self,[ps componentsJoinedByString:@"&"]];
        }
        else
        {
            url = [NSString stringWithFormat:@"%@&%@",self,[ps componentsJoinedByString:@"&"]];
        }
    }
    else
    {
        url = [NSString stringWithFormat:@"%@?%@",self,[ps componentsJoinedByString:@"&"]];
    }
    return url;
}

#pragma mark - new

///星座判断,返回星座
+ (NSString *)yc_getAstroWithMonth:(NSInteger)month day:(NSInteger)day
{
    NSString *astroString = @"魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
    NSString *astroFormat = @"102123444543";
    NSString *result;
    if (month<1||month>12||day<1||day>31){
        return @"错误日期格式!";
    }
    if(month==2 && day>29)
    {
        return @"错误日期格式!!";
    }else if(month==4 || month==6 || month==9 || month==11) {
        if (day>30) {
            return @"错误日期格式!!!";
        }
    }
    result=[NSString stringWithFormat:@"%@",[astroString substringWithRange:NSMakeRange(month*2-(day < [[astroFormat substringWithRange:NSMakeRange((month-1), 1)] intValue] - (-19))*2,2)]];
    
    result = [NSString stringWithFormat:@"%@座",result];
    
    return result;
}

/// 在前面拼接baseUrl
- (NSString *)appendBaseUrl
{
    return [YCAPIBaseUrl stringByAppendingString:self];
}

/// 图片加密返回字符串
+ (NSString *)yc_stringWithBase64FromUIImage:(UIImage *)image
{
    {
        NSData *data = UIImageJPEGRepresentation(image, 1.0f);
        NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        return encodedImageStr;
    }
}

#pragma mark - 正则表达式验证

//手机号码验证
- (BOOL)validateMobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:self];
}

//身份证号
- (BOOL)validateIdentityCard
{
    BOOL flag;
    if (self.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:self];
}

//QQ号码验证
- (BOOL)validateQQ
{
    //1.必须全部都是数字    2.不能以0开头    3.必须是5-15位
    NSString *phoneRegex = @"[1-9]\\d{4,14}";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:self];
}

//url验证
- (BOOL)validateUrl
{
    NSString *phoneRegex = @"http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:self];
}

// 邮箱验证
- (BOOL)validateEmail
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

//车牌号验证
+ (BOOL)validateCarNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:self];
}


@end
